package com.linkhub.oms.admin.config.forest.interceptor;

import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.linkhub.oms.admin.common.exception.ExceptionFactory;
import com.linkhub.oms.admin.modules.shop.service.ShopBizService;
import com.linkhub.oms.common.constant.ShopifyConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.linkhub.oms.common.constant.ShopifyConstant.ACCESS_TOKEN_UNAUTHORIZED_STATUS_CODE;

/**
 * @Description: AppAccessTokenUnauthorizedInterceptor
 * @Author: echo
 * @Date: 2024/3/21 20:42
 * @Version: 1.0
 */
@Slf4j
@Component
public class AppAccessTokenUnauthorizedInterceptor implements Interceptor<ForestResponse<?>> {

    @Resource
    private ShopBizService shopBizService;

    @Override
    public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        String accessToken = getAccessToken(request);
        if (StringUtils.isNotBlank(accessToken) && response.getStatusCode() == ACCESS_TOKEN_UNAUTHORIZED_STATUS_CODE) {
            shopBizService.updateShopUnauthorized(accessToken);
        }

    }

    @Override
    public void afterExecute(ForestRequest request, ForestResponse response) {
        String accessToken = getAccessToken(request);
        if (StringUtils.isNotBlank(accessToken) && response.getStatusCode() == ACCESS_TOKEN_UNAUTHORIZED_STATUS_CODE) {
            throw ExceptionFactory.getI18nBizException("shopify.app.accessToken.error");
        }
    }

    private String getAccessToken(ForestRequest request) {
        return request.getHeaderValue(ShopifyConstant.ACCESS_TOKEN_HEADER);

    }
}
